<?php
namespace Protocols;
class RvHex
{
    
    public static function input($buffer)
    {
        var_dump($buffer);
        $hexBuffer = bin2hex($buffer);
        var_dump(date('H:i:s')."=>".$hexBuffer);
        if(strlen($hexBuffer)==2 && $hexBuffer =='55' ){
            //心跳
            return 1;
        }
        
        if(strlen($hexBuffer)< 14 ){
            //不到命令标识数量，返回0继续等待数据
            return 0;
        }
        if(!in_array(substr($hexBuffer,0,2),['41','42'])){
            return false;
        }
        
        $afterLen = substr($hexBuffer,12,2);
        $len = hexdec($afterLen)+7;
        unset($hexBuffer,$afterLen);
        return $len;
    }

    /**
     * 打包，当向客户端发送数据的时候会自动调用
     * @param string $buffer
     * @return string
     */
    public static function encode($buffer)
    {
        var_dump($buffer);
       $hexBuffer =  hex2bin($buffer);
        var_dump($hexBuffer);
        return $hexBuffer;
    }

    /**
     * 解包，当接收到的数据字节数等于input返回的值（大于0的值）自动调用
     * 并传递给onMessage回调函数的$data参数
     * @param string $buffer
     * @return string
     */
    public static function decode($buffer)
    {
        $hexBuffer =\strtoupper(bin2hex($buffer));
        
        return $hexBuffer;
    }
}